package com.scau.phradmin.common.advices;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scau.phradmin.common.domain.ApiResult;
import com.scau.phradmin.common.exceptions.ErrorCode;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedElement;

/**
 * RestController结果拦截器
 * 将RestController的方法返回值包装成ApiResult返回给前端
 * @author yuzhiyi
 * @date 2018/7/9 10:51
 */
@ControllerAdvice(annotations = RestController.class)
public class ApiResultHandler implements ResponseBodyAdvice {

    private ThreadLocal<ObjectMapper>  mapperThreadLocal = ThreadLocal.withInitial(ObjectMapper::new);

    private Class[] annos = {
            RequestMapping.class,
            GetMapping.class,
            PostMapping.class,
            DeleteMapping.class,
            PutMapping.class
    };

    //对所有RestController的方法进行拦截
    @Override
    @SuppressWarnings("unchecked")
    public boolean supports(MethodParameter returnType, Class converterType) {
        AnnotatedElement element = returnType.getAnnotatedElement();
        for (Class clazz:annos){
            if (element.isAnnotationPresent(clazz)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ApiResult){
            return body;
        }else if (body instanceof String || body instanceof Number){
            ApiResult result = ApiResult.valueOf(String.valueOf(body));
            ObjectMapper mapper = mapperThreadLocal.get();
            try {
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                return mapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else if (body instanceof ErrorCode){
            ApiResult result = new ApiResult(((ErrorCode) body).getCode(),"",null);
            return result;
        }
        else{
            return ApiResult.valueOf(body);
        }
        return null;
    }
}
